<?php


namespace app\admin\controller;


use app\admin\model\TrackdataModel;
use app\admin\model\TracklogModel;
use app\admin\model\TrackspeechcraftModel;
use app\admin\model\TrackxaxisModel;
use app\admin\model\TrackyaxisModel;
use think\Db;

class Tracktable extends Base
{
    /**
     * 地图表格页
     */
    public function index(){
        $x_id = input('x_id');
        $y_id = input('y_id');
        $this->assign([
            'x_id'=>$x_id,
            'y_id'=>$y_id,
            ]);
        return $this->fetch();
    }

    /**
     * 获取下拉数据
     */
    public function get_select_data(){
        $type = input('type');
        $topclass = array();
        if($type=='x'){
            $obj = new TrackxaxisModel();
            $topclass[] =['id'=>0,'name'=>'请选择地区','parentid'=>0,'open'=>false,'checked'=>true];
        }else{
            $obj = new TrackyaxisModel();
            $topclass[] =['id'=>0,'name'=>'请选择产品','parentid'=>0,'open'=>false,'checked'=>true];
        }
        $list = getTree2($obj->get_data($where=[],'id,name,level,parentid',['id'=>'asc']),0,'parentid','id');

        $new = array_merge($topclass,$list);
        return json($new);
    }

    /**
     * 获取表格页数据
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_table_data(){
        $x_id = input('x_id');
        $y_id = input('y_id');

        //根据id获取参数层级
        $x = new TrackxaxisModel();
        $y = new TrackyaxisModel();
        if(!empty($x_id)){
            $x_level = $x->get_level($x_id);
        }else{
            $x_level = 1;
        }
        if(!empty($y_id)){
            $y_level = $y->get_level($y_id);
        }else{
            $y_level = 1;
        }

        $data = array();
        //x轴数据
        $data['x_data'] = $this->table_data_function($x_level,$x_id,$x);
        //y轴数据
        $data['y_data'] = $this->table_data_function($y_level,$y_id,$y);

        $data['x_data'] = $this->fill_data($data['x_data']);
        $data['y_data'] = $this->fill_data($data['y_data']);
        $where_d = array(
            'isdelete'=>0,
            'x_id'=>['in',$this->where_in($data['x_data']['two'])],
            'y_id'=>['in',$this->where_in($data['y_data']['two'])],
        );

        //数据域数据
        $d = new TrackdataModel();
        $data['d_data'] = $d->get_select($where_d);

        $res = array(
          'code'=>0,
          'msg'=>'获取成功',
          'data'=>$data
        );
        return json($res);
    }

    /**
     * 详情页
     */
    public function details(){
        $id=input('id');
        $x_id=input('x_id');
        $y_id=input('y_id');
        $this->assign([
            'id'=>$id,
            'x_id'=>$x_id,
            'y_id'=>$y_id
        ]);
        return $this->fetch('details');
    }

    /**
     * 保存基础信息
     */
    public function ajaxSaveData(){
        if(request()->isAjax()){
            $param = input('post.');
            $d = new TrackdataModel();
			$param['survey']=2;
			$param['market']=0;
			$param['survay_user']=session('user.id');
            if(!empty($param['id'])){
                
                $res = $d->edit($param);
            }else{
                $res = $d->add($param);
            }
            return json($res);
        }
        return json(['code'=>3,'msg'=>'非法访问']);
    }

    /**
     * 获取基础信息
     * @return \think\response\Json
     */
    public function get_data_details(){
        if(request()->isAjax()){
            $id = input('id');
            $d = new TrackdataModel();
            $data['data'] = !empty($id)?$d->get_data($id):'';
            $data['code'] = !empty($data['data'])?1:0;
            return json($data);
        }
        return json(['code'=>0,'msg'=>'非法请求']);
        //获取基本数据
    }

    /**
     * 获取时间轴数据
     */
    public function time_line(){
        if (request()->isAjax()) {
            $d_id = input('d_id');
            $l = new TracklogModel();
            $data = $l->get_time_line($d_id);
            return $this->success('查询成功', '', $data);
        }
    }

    /**
     * 跟进进度示意图数据
     *
     */
    public function get_progress(){
        if(request()->isAjax()){
            $d_id = input('d_id');
            $data = array();

            array_push($data,['id'=>0,'title'=>'未跟进','level'=>0,'create_time'=>0]);
            if(!empty($d_id)){
                $l = new TracklogModel();
                $res = $l->get_log($d_id,$data);
                $data = $res['data'];
            }
            array_push($data,['id'=>10000000,'title'=>'结束跟进','level'=>count($data),'create_time'=>0]); //

            if(!empty($d_id)){
                $d = new TrackdataModel();
                $set = $d->get_data($d_id);
                if($set['market']==1){
                    $now = $res['count'];
                }elseif($set['market']==2){
                    $now = $res['count']+1;
                }else{
                    $now = 1;
                }
            }else{
                $now = 1;
            }

            $res = array(
                'code'=>1,
                'msg'=>'查询成功',
                'data'=>array(
                    'list'=>$data,
                    'now'=>$now,
                )
            );
            return json($res);
        }
        $res = array(
            'code'=>-1,
            'msg'=>'查询失败',
        );
        return json($res);
    }

    /**
     * 保存跟进日志
     */
    public function ajaxSaveLog(){
        if(request()->isAjax()){
            $input = input('post.');
            if(isset($input['id'])){
                //补全数据
                $log = '';
                if($input['flag'] == 0){
                    $log .= '用户'.session('user.name').'对'.$input['id'].'号项目进行了跟进.';
                    $market = 1;
                }elseif($input['flag'] == 1){
                    $log .= '用户'.session('user.name').'终止了'.$input['id'].'号项目';
                    $market = 3;
                }elseif($input['flag'] == 2){
                    $log .= '用户'.session('user.name').'完结了'.$input['id'].'号项目';
                    $market = 2;
                }
                $l = new TracklogModel();
                $level = $l->get_time_line($input['id']);
                if(empty($level)){
                    $level = 1;
                }else{
                    $level = count($level)+1;
                }
                $param = array(
                    'user_id'=>session('user.id'),
                    'type'=>$input['title'],
                    'ip'=>session('user.login_ip'),
                    'log'=>$log,
                    'speak'=>$input['speak'],
                    'relation_id'=>$input['id'],
                    'level'=>$level,
                );
                $msg = $l->add($param);
                if($msg['code']==1){
                    $d = new TrackdataModel();
                    $where = array(
                      'id'=>$input['id'],
                      'market'=>$market,
                    );
                    $d->edit($where);
                }
            }else{
                $msg = array(
                    'code'=>-1,
                    'msg'=>'该项目未调研,请前往基本资料进行填写'
                );
            }
            return json($msg);
        }
    }

    /**
     * 话术列表
     */
    public function get_speechcraft_list(){
        if(request()->isAjax()){
            $param = input('param.');
            $limit = $param['limit'];
            $page  = $param['page'];
            $s = new TrackspeechcraftModel();
            $where = array(
                'isdelete'=>0
            );
            $list = $s->get_page_list($where,$limit,$page);
            $data = array(
                'code' => '200',
                'msg' => '请求成功',
                'count' => $list['total'],
                'data' => $list['data'],
            );
            return json($data);
        }
    }

    /**
     * 获取下载列表
     */
    public function get_down_list(){
        if(request()->isAjax()){
            $type = input('type');
            $limit = input('limit');
            $page = input('page');
            $where['a.main_id'] = input('id');

            $where['a.isdelete']=0;

            if($type==1){
                $where['a.table_name'] = 'track_yaxis';
                $list = Db::name('attachment_relevancy')->alias('a')
                    ->join('jmzhfs_file_record b','a.file_record_id=b.id','LEFT')
                    ->where($where)
                    ->field('a.main_id,b.id as file_id,b.name,b.network_path,b.md5_value,b.size')
                    ->paginate($limit,false,['page'=>$page])
                    ->toArray();
                $data = array(
                    'code' => '200',
                    'msg' => '请求成功',
                    'count' => $list['total'],
                    'data' => $list['data'],
                );
            }elseif($type==2){
                $where['a.table_name'] = 'track_data';

                $list = Db::name('attachment_relevancy')
                    ->alias('a')
                    ->join('jmzhfs_file_record b','a.file_record_id=b.id','LEFT')
                    ->where($where)
                    ->field('a.main_id,b.id as file_id,b.name,b.network_path,b.md5_value,b.size')
                    ->select();
                $aa = Db::name('attachment_relevancy')->getLastSql();
                    if($list){
                        $data['data'] = $list;
                        $data['code'] = 1;
                        $data['msg']  = '获取数据成功';
                    }else{
                        $data['data'] = '';
                        $data['code'] = -1;
                        $data['msg']  = '获取数据为空';
                    }
            }
            return json($data);
        }
    }

    /**
     * 数据填充
     */
    public function fill_data($source){
        if(empty($source['two'])){
            $source['two'] = $source['one'];
        }else{
            $source = $this->existent($source);
        }
        return $source;
    }

    /**
     * 验证是否有下级头信息
     */
    public function existent($source){
        foreach($source['one'] as $key=>$val){
            $judge = false;
            $temp = $val;
            foreach ($source['two'] as $k=>$v){
                if($val['id']==$v['parentid']){
                    $judge = true;
                    break;
                }
            }
            if($judge === false){
                unset($source['one'][$key]);
                array_push($source['one'],$temp);
                array_push($source['two'],$temp);
            }
        }
        return $source;
    }

    /**
     * 数据获取方法
     */
    public function table_data_function($level,$id,$obj){
        if($level == 1 || $level == 2){
            $where_one['level'] = 2;
            $where_two['level'] = 3;
        }
        $data = array();
        switch (true){
            case ($level==1 || $level==2):
                if($level==1){
                    !empty($id)?$where_one['parentid']=$id:"";
                }else{
                    !empty($id)?$where_one['id']=$id:"";
                }
                $data['one'] = $obj->get_data($where_one,'id,name,level,parentid',['id'=>'asc']);
                $ids = array();
                foreach($data['one'] as $k=>$v){
                    $ids[] = $v['id'];
                }
                $where_two['parentid'] = array('in',$ids);
            //y轴数据
            case ($level==3);
                if($level == 3){
                    $where_two['level'] = 3;
                    !empty($id)?$where_two['id']=$id:"";
                    $data['one'] = $obj->get_data($where_two,'id,name,level,parentid',['parentid'=>'asc']);
                }else{
                    $data['two'] = $obj->get_data($where_two,'id,name,level,parentid',['parentid'=>'asc']);
                }
                break;
        }
        return $data;
    }

    /**
     * 保存上传文件的地址（关联绑定）
     * @return mixed
     * @author: pan
     * @Date: times
     */
    public function ajaxSaveDetails(){
        if(request()->isAjax()){
            $param = request()->param();
            $menmodule = new TrackdataModel();
            $result = $menmodule->saveDetails($param);
            return $result;
        }
    }

    /**
     * 下载
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function download()
    {
        $complete_path = input('path');
        $name = input('name');
        // 检查文件是否存在
        if (!file_exists($complete_path)){
            $this->error('文件未找到');
        }else{
            // 打开文件
            $file1 = fopen($complete_path, "r");
            // 输入文件标签
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length:".filesize($complete_path));
            header('Content-Disposition: attachment; filename=' . $name);
            header('Content-Type: application/octet-stream; name=' . $name);
            ob_clean();     // 重点！！！可以清除文件中多余的路径名以及解决乱码的问题
            flush();        // 重点！！！！：
            //输出文件内容
            //读取文件内容并直接输出到浏览器
            $content = fread($file1, filesize($complete_path));
            echo $content;
            exit();
        }
    }


    /**
     * 获取id
     */
    public function where_in($data){
        $array = array();
        foreach($data as $k=>$v){
            $array[] = $v['id'];
        }
        return $array;
    }
}